package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;


    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //处理异常
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //商品数据都是在购物车中，提交后向orders表以及orders_detail中插入相应的数据

        Orders order = new Orders();
        //订单号=用户id+时间戳
        String number = String.valueOf(BaseContext.getCurrentId() + System.currentTimeMillis());
        order.setNumber(number);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setUserId(BaseContext.getCurrentId());
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setPhone(address.getPhone());
        order.setConsignee(address.getConsignee());
        order.setAddress(address.getDistrictName());

        //order.setRemark();


        BeanUtils.copyProperties(ordersSubmitDTO, order);

        orderMapper.insert(order);

        List<OrderDetail> orderDetailList = new ArrayList<>();
        list.forEach(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(order.getId());
            //orderDetailMapper.insert(orderDetail);
            orderDetailList.add(orderDetail);
        });

        //使用批量插入
        orderDetailMapper.insertBatch(orderDetailList);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime()).build();

        return orderSubmitVO;
    }

    private String getOrderDishesStr(List<OrderDetail> orderDetailList) {
        // 查询订单菜品详情信息（订单中的菜品和数量）

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());


        //查询当前用户的所有订单
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());
        //orders.setStatus(ordersPageQueryDTO.getStatus());
        BeanUtils.copyProperties(ordersPageQueryDTO,orders);
        Page<OrderVO> p = (Page<OrderVO>) orderMapper.list(orders,ordersPageQueryDTO.getBeginTime(),
                ordersPageQueryDTO.getEndTime());

        p.forEach(orderVO -> {
            List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
            orderVO.setOrderDishes(getOrderDishesStr(orderDetailList));
        });
        //System.out.println(p.getTotal());
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public OrderVO getById(Long id) {

        Orders orders = new Orders();
        orders.setId(id);
        List<OrderVO> list = orderMapper.list(orders,null,null);

        if (list != null && !list.isEmpty()) {
            Orders order = list.get(0);

            List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(order.getId());

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVO.setOrderDishes(getOrderDishesStr(orderDetailList));
            return orderVO;
        } else {
            return null;
        }

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);


        //跳过微信支付注释了，下面这里，不通过公司注册商户无法完成
        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
//        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
//        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
//
//        //发现没有将支付时间 check_out属性赋值，所以在这里更新
//        LocalDateTime check_out_time = LocalDateTime.now();

        //订单完成后更新订单的状态
        //获取订单号码

        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /***
     * 取消订单
     * @param ordersCancelDTO 订单id
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        //根据id查询，实际上只会查到一个或者0个
        List<OrderVO> list = orderMapper.list(orders,null,null);

        if (list != null && !list.isEmpty()) {
            orders = list.get(0);

            //更新orders表
            orders.setStatus(Orders.CANCELLED);
            orders.setPayStatus(Orders.REFUND);
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }

    }

    //获取订单统计
    @Override
    public OrderStatisticsVO getOrderStatistics() {
        List<OrderVO> list = orderMapper.list(null,null,null);
        Integer toBeConfirmed = 0;
        Integer confirmed = 0;
        Integer deliveryInProgress = 0;


        for (OrderVO orderVO : list) {
            Integer status = orderVO.getStatus();
            if ( Orders.TO_BE_CONFIRMED==status) {
                toBeConfirmed++;
            } else if (Orders.CONFIRMED==status) {
                confirmed++;
            } else if (Orders.DELIVERY_IN_PROGRESS==status) {
                deliveryInProgress++;
            }
        }

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);


        return orderStatisticsVO;
    }

    //商家接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders=new Orders();
        orders.setId(ordersConfirmDTO.getId());
        List<OrderVO> list = orderMapper.list(orders, null, null);
        if(list!=null&&!list.isEmpty()){
            OrderVO orderVO = list.get(0);
            //只有处于待接单的订单才能被接单
            if(Orders.TO_BE_CONFIRMED!=orderVO.getStatus()){
                throw  new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            BeanUtils.copyProperties(orderVO,orders);
            orders.setStatus(Orders.CONFIRMED);
            orderMapper.update(orders);

        }
    }


    //商家拒单
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders=new Orders();
        orders.setId(ordersRejectionDTO.getId());
        List<OrderVO> list = orderMapper.list(orders, null, null);
        if(list!=null&&!list.isEmpty()){
            OrderVO orderVO = list.get(0);
            //只有处于待接单的订单才能被拒单
            if(Orders.TO_BE_CONFIRMED!= orderVO.getStatus()){
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            BeanUtils.copyProperties(orderVO,orders);
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setPayStatus(Orders.REFUND);//退款
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }
    }


    //派送订单
    @Override
    public void delivery(Long id) {
        Orders orders=new Orders();
        orders.setId(id);
        List<OrderVO> list = orderMapper.list(orders, null, null);
        if(list!=null&&!list.isEmpty()){
            OrderVO orderVO = list.get(0);
            //只有处于已接单的订单才能被派送
            if(Orders.CONFIRMED!=orderVO.getStatus()){
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            BeanUtils.copyProperties(orderVO,orders);
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

            orderMapper.update(orders);
        }
    }


    //完成订单
    @Override
    public void complete(Long id) {
        Orders orders=new Orders();
        orders.setId(id);
        List<OrderVO> list = orderMapper.list(orders, null, null);
        if(list!=null&&!list.isEmpty()){
            OrderVO orderVO = list.get(0);
            //只有处于在派送订单才能被完成
            if(Orders.DELIVERY_IN_PROGRESS!=orderVO.getStatus()){
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            BeanUtils.copyProperties(orderVO,orders);
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());

            orderMapper.update(orders);
        }
    }

    //催单
    @Override
    public void remind(Long id) {
        Orders orders=new Orders();
        orders.setId(id);
        List<OrderVO> list = orderMapper.list(orders, null, null);

        if(list!=null &&!list.isEmpty() ){

            OrderVO orderVO = list.get(0);
            if(Orders.TO_BE_CONFIRMED!= orderVO.getStatus()){
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            Map<String,Object> map=new HashMap<>();
            //type 1表示来单提醒，type 2表示催单
            map.put("type",2);
            map.put("orderId",id);
            map.put("content","订单号："+orderVO.getNumber());

            String json= JSON.toJSONString(map);
            webSocketServer.sendToAllClient(json);
        }

    }


    /**
     * 支付成功，修改订单状态
     *
     * @param number
     */
    public void paySuccess(String number) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(number);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map<String,Object> map=new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+ordersDB.getNumber());

        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

}
